package cn.gzsxt.interceptor;

import java.lang.reflect.Method;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.gzsxt.annotation.TokenForm;

public class TokenFormInterceptor implements HandlerInterceptor {
	
	private static final Logger LOGGER=LogManager.getLogger(TokenFormInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//获得请求对应的方法的注解
		//用于获得执行方法的method对象
		HandlerMethod handlerMethod=(HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		HttpSession session = request.getSession();
		TokenForm tokenForm = method.getDeclaredAnnotation(TokenForm.class);
		if (tokenForm!=null) {
			//1.判断是否是进入需要防重提交表单的请求
			if (tokenForm.create()==true) {
				//创建一个唯一的字符串放在session
				String token = UUID.randomUUID().toString();
				session.setAttribute("token", token);
				LOGGER.debug("Token:"+token);
			}
			
			if (tokenForm.remove()==true) {
				//验证表单是否有和session对应的token
				String parameterToken = request.getParameter("token");
				if (parameterToken.equals(session.getAttribute("token"))) {
					session.removeAttribute("token");
					return true;
				}else{
					//获得指定的跳转路径
					String invoke = request.getParameter("token.invoke");
					request.getRequestDispatcher(invoke).forward(request, response);
					return false;
				}
				
			}
			
			
			
		}
	    //如果本来就不是一个重提交请求，直接跳过
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
